package bb.lanxing.adapter.mine;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.github.mikephil.charting.utils.Utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import bb.lanxing.R;
import bb.lanxing.lib.widget.SectionedRecyclerViewAdapter;
import bb.lanxing.model.database.IWorkout;
import bb.lanxing.model.database.Workout;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.DateUtil;
import bb.lanxing.util.DensityUtil;
import bb.lanxing.util.SpliceBitmapUtil;
import bb.lanxing.util.WorkoutTitleUtil;

public class HistoryListAdapter extends SectionedRecyclerViewAdapter<HistoryListAdapter.HeaderViewHolder,
        HistoryListAdapter.ItemViewHolder, RecyclerView.ViewHolder>
        implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private RecyclerView recyclerView;
    private String[] months;

    private boolean chooseMode = false;

    private int chooseSize;

    private OnItemClickListener<Workout> onItemClickListener;

    private ArrayList<MonthDesc> monthDataSet = new ArrayList<>();
    private LinkedHashMap<String, Workout> chooseWorkouts = new LinkedHashMap<>();

    public HistoryListAdapter(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        months = recyclerView.getContext().getResources().getStringArray(R.array.month_array);
    }

    public static class MonthDesc {
        public String month;
        public List<Workout> itemDataSet = Collections.emptyList();
        public long distance = 0;
        public long duration = 0;
        public double credits = Utils.DOUBLE_EPSILON;
    }

    public interface OnItemClickListener<T> {
        boolean onItemClick(int pos, T item, View v, boolean isChecked);
    }

    @Override
    protected boolean hasFooterInSection(int section) {
        return false;
    }

    @Override
    protected void onBindSectionFooterViewHolder(RecyclerView.ViewHolder holder, int section) {
    }

    @Override
    protected RecyclerView.ViewHolder onCreateSectionFooterViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onClick(View v) {
        int childAdapterPosition;
        if (chooseMode) {
            int childAdapterPosition2 = recyclerView.getChildAdapterPosition(v);
            if (childAdapterPosition2 != -1) {
                Workout workout = this.monthDataSet.get(getSectionForPosition(childAdapterPosition2)).itemDataSet.get(getPositionInSection(childAdapterPosition2));
                boolean z = !this.chooseWorkouts.containsKey(workout.getUuid());
                if (!z || this.chooseWorkouts.size() < this.chooseSize) {
                    OnItemClickListener<Workout> onItemClickListener = this.onItemClickListener;
                    if (onItemClickListener == null || onItemClickListener.onItemClick(childAdapterPosition2, workout, v, z)) {
                        if (z) {
                            this.chooseWorkouts.put(workout.getUuid(), workout);
                        } else {
                            this.chooseWorkouts.remove(workout.getUuid());
                        }
                        notifyItemChanged(childAdapterPosition2);
                    }
                }
            }
        } else if (this.onItemClickListener != null && (childAdapterPosition = this.recyclerView.getChildAdapterPosition(v)) != -1) {
            this.onItemClickListener.onItemClick(childAdapterPosition,
                    this.monthDataSet.get(getSectionForPosition(childAdapterPosition)).itemDataSet.get(getPositionInSection(childAdapterPosition)), v, false);
        }
    }

    public void setOnItemClickListener(OnItemClickListener<Workout> onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int childAdapterPosition;
        if (isChecked && this.chooseWorkouts.size() >= this.chooseSize) {
            buttonView.setChecked(false);
            return;
        }
        Workout workout = (Workout) buttonView.getTag();
        int findItemPosition = findItemPosition(workout);
        if (findItemPosition >= 0) {
            View view = (View) buttonView.getParent().getParent();
            if (this.onItemClickListener == null || ((childAdapterPosition = this.recyclerView.getChildAdapterPosition(view)) != -1 && this.onItemClickListener.onItemClick(childAdapterPosition, workout, view, isChecked))) {
                if (isChecked) {
                    this.chooseWorkouts.put(workout.getUuid(), workout);
                } else {
                    this.chooseWorkouts.remove(workout.getUuid());
                }
                notifyItemChanged(findItemPosition);
                return;
            }
            buttonView.setChecked(!isChecked);
        }
    }

    public void addMonthData(boolean clear, List<MonthDesc> list) {
        int itemCount = getItemCount();
        if (clear && !this.monthDataSet.isEmpty()) {
            this.monthDataSet.clear();
            notifyItemRangeRemoved(0, itemCount);
            itemCount = 0;
        }
        this.monthDataSet.addAll(list);
        notifyItemRangeInserted(itemCount, getItemCount());
    }

    public void removeItem(int position) {
        int sectionForPosition = getSectionForPosition(position);
        int positionInSection = getPositionInSection(position);
        MonthDesc monthDesc = this.monthDataSet.get(sectionForPosition);
        if (monthDesc == null || monthDesc.itemDataSet.remove(positionInSection) == null) {
            return;
        }
        notifyItemRemoved(position);
        if (monthDesc.itemDataSet.isEmpty()) {
            this.monthDataSet.remove(monthDesc);
            notifyItemRemoved(position - 1);
        }
    }

    public void updateMonth(MonthDesc monthDesc) {
        int i = 0;
        while (true) {
            if (i >= this.monthDataSet.size()) {
                break;
            }
            MonthDesc monthDesc2 = this.monthDataSet.get(i);
            if (monthDesc2.month.equals(monthDesc.month)) {
                monthDesc2.credits = monthDesc.credits;
                monthDesc2.distance = monthDesc.distance;
                monthDesc2.duration = monthDesc.duration;
                break;
            }
            i++;
        }
        if (i < this.monthDataSet.size()) {
            notifyItemChanged(getItemPosition(i));
        }
    }

    public void updateItem(Workout workout, int position) {
        int sectionForPosition = getSectionForPosition(position);
        int positionInSection = getPositionInSection(position);
        MonthDesc monthDesc = this.monthDataSet.get(sectionForPosition);
        if (monthDesc != null) {
            monthDesc.itemDataSet.set(positionInSection, workout);
            notifyItemChanged(position);
        }
    }

    public void updateItem(Workout workout) {
        int findItemPosition = findItemPosition(workout);
        if (findItemPosition >= 0) {
            updateItem(workout, findItemPosition);
        }
    }

    public MonthDesc getMonthItem(int position) {
        return this.monthDataSet.get(getSectionForPosition(position));
    }

    public void removeItemById(long workoutId) {
        int i = 0;
        while (true) {
            if (i >= this.monthDataSet.size()) {
                break;
            }
            List<Workout> list = this.monthDataSet.get(i).itemDataSet;
            int i2 = 0;
            while (i2 < list.size() && workoutId != list.get(i2).getId()) {
                i2++;
            }
            if (i2 < list.size()) {
                list.remove(i2);
                break;
            }
            i++;
        }
        if (i < this.monthDataSet.size() && this.monthDataSet.get(i).itemDataSet.isEmpty()) {
            this.monthDataSet.remove(i);
        }
        notifyDataSetChanged();
    }

    public void clearData() {
        if (this.monthDataSet.isEmpty()) {
            return;
        }
        int itemCount = getItemCount();
        this.monthDataSet.clear();
        notifyItemRangeRemoved(0, itemCount);
    }

    public int findItemPositionF(Workout workout) {
        if (workout == null) {
            return -1;
        }
        int i = 0;
        int i2 = 0;
        while (true) {
            if (i >= this.monthDataSet.size()) {
                break;
            }
            List<Workout> list = this.monthDataSet.get(i).itemDataSet;
            int i3 = 0;
            while (i3 < list.size() && workout.getServerId() != list.get(i3).getServerId()) {
                i3++;
            }
            if (i3 < list.size()) {
                i2 = i3;
                break;
            }
            i++;
            i2 = i3;
        }
        if (i < this.monthDataSet.size()) {
            int i4 = 0;
            for (int i5 = 0; i5 < i; i5++) {
                i4 += getItemCountForSection(i5) + 1;
            }
            return i4 + i2 + 1;
        }
        return -1;
    }

    private int findItemPosition(Workout workout) {
        if (workout == null) {
            return -1;
        }
        int i = 0;
        int i2 = 0;
        while (true) {
            if (i >= this.monthDataSet.size()) {
                break;
            }
            List<Workout> list = this.monthDataSet.get(i).itemDataSet;
            int i3 = 0;
            while (i3 < list.size() && !workout.equals(list.get(i3))) {
                i3++;
            }
            if (i3 < list.size()) {
                i2 = i3;
                break;
            }
            i++;
            i2 = i3;
        }
        if (i < this.monthDataSet.size()) {
            int i4 = 0;
            for (int i5 = 0; i5 < i; i5++) {
                i4 += getItemCountForSection(i5) + 1;
            }
            return i4 + i2 + 1;
        }
        return -1;
    }

    public ArrayList<MonthDesc> getMonthDataSet() {
        return this.monthDataSet;
    }

    @Override
    public int getSectionCount() {
        ArrayList<MonthDesc> arrayList = this.monthDataSet;
        if (arrayList == null) {
            return 0;
        }
        return arrayList.size();
    }

    @Override
    protected int getItemCountForSection(int section) {
        ArrayList<MonthDesc> arrayList = this.monthDataSet;
        if (arrayList == null) {
            return 0;
        }
        return arrayList.get(section).itemDataSet.size();
    }

    @Override
    public HeaderViewHolder onCreateSectionHeaderViewHolder(ViewGroup parent, int viewType) {
        return new HeaderViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history_list_header, parent, false));
    }

    @Override
    public ItemViewHolder onCreateItemViewHolder(ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history_list_content, parent, false);
        inflate.setOnClickListener(this);
        ItemViewHolder itemViewHolder = new ItemViewHolder(inflate);
        return itemViewHolder;
    }

    @Override
    public void onBindSectionHeaderViewHolder(HeaderViewHolder holder, int section) {
        if (section < 0 || section >= this.monthDataSet.size()) {
            return;
        }
        MonthDesc monthDesc = this.monthDataSet.get(section);
        holder.monthText.setText(this.recyclerView.getContext().getString(R.string.history_month_total, monthDesc.month));
        holder.distanceText.setText(CommonUtil.getFormatDistance(monthDesc.distance));
        holder.durationText.setText(DateUtil.format(monthDesc.duration * 1000, 2));
        holder.countText.setText(String.valueOf(monthDesc.itemDataSet.size()));
        holder.scoreText.setText(String.valueOf(Math.round(monthDesc.credits)));
        holder.itemView.postInvalidate();
    }

    @Override
    public void onBindItemViewHolder(ItemViewHolder holder, int section, int index) {
        String string;
        int color;
        boolean z;
        Workout workout = this.monthDataSet.get(section).itemDataSet.get(index);
        switch (workout.getSport()) {
            case Workout.TYPE_CYCLING ->
                    holder.mapThumb.setImageResource(R.drawable.ic_data_active_ride);
            case Workout.TYPE_RUNNING ->
                    holder.mapThumb.setImageResource(R.drawable.ic_data_active_run);
            case Workout.TYPE_WALKING ->
                    holder.mapThumb.setImageResource(R.drawable.ic_data_active_walk_slowly);
            case Workout.TYPE_SKIING ->
                    holder.mapThumb.setImageResource(R.drawable.ic_sport_data_skiing);
            case Workout.TYPE_SWIMMING ->
                    holder.mapThumb.setImageResource(R.drawable.ic_sport_data_swim_indoor);
            case Workout.TYPE_TRAINING ->
                    holder.mapThumb.setImageResource(R.drawable.ic_sport_data_barbell_training);
            case Workout.TYPE_OTHER ->
                    holder.mapThumb.setImageResource(R.drawable.ic_sport_data_car);
            case Workout.TYPE_INDOOR_BIKE ->
                    holder.mapThumb.setImageResource(R.drawable.ic_sport_data_indoor_bike);
//            default -> holder.mapThumb.setImageResource(R.drawable.sport_data_car);
        }
        if (TextUtils.isEmpty(workout.getTitle())) {
            holder.titleText.setText(WorkoutTitleUtil.buildWorkoutDefaultTitle(this.recyclerView.getContext(), workout));
        } else {
            holder.titleText.setText(workout.getTitle());
        }
        holder.titleText.setTextColor(this.recyclerView.getResources().getColor(R.color.history_item_date_text_color));
        if ((workout.getDistance() == Utils.DOUBLE_EPSILON
                && (workout.getSport() == Workout.TYPE_INDOOR_BIKE || workout.getSport() == Workout.TYPE_BIKE_TRAINER || workout.getSport() == Workout.TYPE_VIRTUAL_ACTIVITY))
                || workout.getLocSource() == Workout.LOCATION_SOURCE_XOSS_X2P) {
            if (workout.getDuration() > 0) {
                long duration = workout.getDuration() / 3600;
                long duration2 = (workout.getDuration() - (3600 * duration)) / 60;
                StringBuffer stringBuffer = new StringBuffer();
                if (duration > 0) {
                    stringBuffer.append(duration);
                    stringBuffer.append("h");
                    z = true;
                } else {
                    z = false;
                }
                stringBuffer.append(duration2);
                stringBuffer.append("m");
                if (!z) {
                    stringBuffer.append((workout.getDuration() % 60) + "s");
                }
                SpannableString spannableString = new SpannableString(stringBuffer.toString());
                if (stringBuffer.toString().contains("h")) {
                    spannableString.setSpan(new AbsoluteSizeSpan(DensityUtil.dp2px(20.0f)),
                            stringBuffer.toString().indexOf("h"), stringBuffer.toString().indexOf("h") + 1, 0);
                }
                spannableString.setSpan(new AbsoluteSizeSpan(DensityUtil.dp2px(20.0f)),
                        stringBuffer.toString().indexOf("m"), stringBuffer.toString().indexOf("m") + 1, 0);
                if (stringBuffer.toString().contains("s")) {
                    spannableString.setSpan(new AbsoluteSizeSpan(DensityUtil.dp2px(20.0f)),
                            stringBuffer.toString().indexOf("s"), stringBuffer.toString().indexOf("s") + 1, 0);
                }
                holder.distanceText.setText(spannableString);
                holder.distanceTextParam.setText("");
            }
        } else {
            holder.distanceText.setText(CommonUtil.getFormatDistance(workout.getDistance()));
        }
        Context context = this.recyclerView.getContext();
        if (workout.getCategory() == IWorkout.CATEGORY_MERGE) {
            holder.mIvMergePro.setVisibility(View.VISIBLE);
            holder.scoreText.setVisibility(View.GONE);
            holder.scoreUnitText.setVisibility(View.GONE);
        } else {
            holder.mIvMergePro.setVisibility(View.GONE);
            holder.scoreText.setVisibility(View.VISIBLE);
            holder.scoreUnitText.setVisibility(View.VISIBLE);
            if (workout.getServerId() > 0) {
                string = context.getString(R.string.hot_value);
                holder.scoreText.setText(String.valueOf(Math.round(workout.getCredits())));
                color = context.getResources().getColor(R.color.global_orange_color);
            } else {
                holder.scoreText.setText("");
                string = context.getString(R.string.hot_not_upload);
                color = context.getResources().getColor(R.color.grey_999999);
            }
            holder.scoreText.setTextColor(color);
            holder.scoreUnitText.setTextColor(color);
            holder.scoreUnitText.setText(string);
        }
        holder.overlap.setVisibility(workout.getHidden() == 1 ? View.VISIBLE : View.GONE);
        Drawable generateWorkoutFeatures = SpliceBitmapUtil.generateWorkoutFeatures(context,
                workout.getCadenceSource(), workout.getHeartSource(), workout.getLocSource(),
                workout.hasMatchedSegment(), workout.getSlopeGradeMax(), workout.isThreedWorkout());
        holder.dataSourceType.setVisibility(generateWorkoutFeatures != null ? View.VISIBLE : View.GONE);
        holder.dataSourceType.setImageDrawable(generateWorkoutFeatures);

        getItemCountForSection(section);
        if (this.chooseMode) {
            if (this.chooseWorkouts.get(workout.getUuid()) != null) {
                setCheckboxWithoutListener(holder.checkBox, true);
            } else {
                setCheckboxWithoutListener(holder.checkBox, false);
            }
            holder.checkBox.setTag(workout);
            holder.checkBox.setVisibility(View.VISIBLE);
            return;
        }
        holder.checkBox.setVisibility(View.GONE);
    }

    private void setCheckboxWithoutListener(CheckBox checkbox, boolean checked) {
        checkbox.setOnCheckedChangeListener(null);
        checkbox.setChecked(checked);
        checkbox.setOnCheckedChangeListener(this);
    }

    @Override
    public CharSequence getSectionTitle(int section) {
        if (monthDataSet == null) {
            return null;
        }
        return months[Integer.parseInt(monthDataSet.get(section).month) - 1];
    }

    @Override
    public View getSectionHeaderView(ViewGroup parent, View oldView, int section, int viewType) {
        HeaderViewHolder headerViewHolder;
        if (oldView == null) {
            headerViewHolder = onCreateSectionHeaderViewHolder(parent, viewType);
            headerViewHolder.itemView.setTag(headerViewHolder);
        } else {
            headerViewHolder = (HeaderViewHolder) oldView.getTag();
        }
        onBindSectionHeaderViewHolder(headerViewHolder, section);
        headerViewHolder.line.setVisibility(View.VISIBLE);
        return headerViewHolder.itemView;
    }

    public void setChooseMode(boolean chooseMode, int chooseSize) {
        this.chooseMode = chooseMode;
        this.chooseSize = chooseSize;
        notifyDataSetChanged();
    }

    public ArrayList<Workout> getSelectedItem() {
        return new ArrayList<>(this.chooseWorkouts.values());
    }

    public int getSelectedCount() {
        return this.chooseWorkouts.size();
    }

    public double getSelectedMileage() {
        double d = Utils.DOUBLE_EPSILON;
        for (Map.Entry<String, Workout> entry : this.chooseWorkouts.entrySet()) {
            d += entry.getValue().getDistance();
        }
        return d;
    }

    public static class HeaderViewHolder extends RecyclerView.ViewHolder {
        private final TextView countText;
        private final TextView distanceText;
        private final TextView durationText;
        private final View line;
        private final TextView monthText;
        private final TextView scoreText;

        HeaderViewHolder(View itemView) {
            super(itemView);
            this.monthText = itemView.findViewById(R.id.item_history_header_month);
            this.distanceText = itemView.findViewById(R.id.item_history_header_distance);
            this.durationText = itemView.findViewById(R.id.item_history_header_duration);
            this.countText = itemView.findViewById(R.id.item_history_header_count);
            this.scoreText = itemView.findViewById(R.id.item_history_header_score);
            this.line = itemView.findViewById(R.id.item_history_header_line);
        }
    }

    public static class ItemViewHolder extends RecyclerView.ViewHolder {
        private final CheckBox checkBox;
        private final TextView distanceText;
        private final TextView distanceTextParam;
        private final ImageView mIvMergePro;
        private final ImageView mapThumb;
        private final View overlap;
        private final TextView scoreText;
        private final TextView scoreUnitText;
        private final TextView titleText;
        private final ImageView dataSourceType;

        ItemViewHolder(View itemView) {
            super(itemView);
            this.mapThumb = itemView.findViewById(R.id.item_history_content_thumb);
            this.titleText = itemView.findViewById(R.id.item_history_content_title);
            this.distanceText = itemView.findViewById(R.id.item_history_content_distance);
            this.distanceTextParam = itemView.findViewById(R.id.item_history_content_distance_param);
            this.scoreText = itemView.findViewById(R.id.item_history_content_score);
            this.scoreUnitText = itemView.findViewById(R.id.item_history_content_score_unit);
            this.mIvMergePro = itemView.findViewById(R.id.iv_merge_pro);
            this.checkBox = itemView.findViewById(R.id.item_history_choose_checkbox);
            this.overlap = itemView.findViewById(R.id.item_history_hide_overlap);
            this.dataSourceType = itemView.findViewById(R.id.cadenceTypeIcon);
        }
    }
}